import {
  Layout,
  Card,
  Button,
  Radio,
  Space,
  message,
  InputNumber,
  Form,  Divider, Modal
} from 'antd';
import React, {useEffect, useState} from 'react';
import './ShopPage.css';
import {buyPointsUsingPost, getLoginUserUsingGet, isPayUsingPost} from "@/services/openAPI-backend/userController";
import {keyframes} from "antd-style";
import { Link, history } from '@umijs/max';
const ShopPage = () => {
  const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<'wechat'  | 'alipay'>('wechat');
  const [loginUser,setLoginUser] = useState<API.User>()
  const [agreementAccepted, setAgreementAccepted] = useState(false);
  const [inputValue, setInputValue] = useState<number>(100);
  const [actualPayAmount, setActualPayAmount] = useState<number>(() => Math.floor(inputValue / 10));
  const [sendValue, setSendValue] = useState<number>(13);
  const fadeIn = keyframes`
    0% {
      transform: translateY(50%);
    }
    100% {
      transform: translateY(0);
    }
  `;
  const handleInputChange = (value: number | undefined) => {
    if (typeof value === 'number') {
      setInputValue(value);
      setActualPayAmount(value / 10);
      setSendValue(Math.floor(value/8));
    }
  };
  const handleAgreementChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setAgreementAccepted(event.target.checked);
  };
  const handlePaymentMethodClick = (method: 'wechat' | 'alipay') => {
    setSelectedPaymentMethod(method);
  };
  const wechatButtonStyle = {
    marginRight: 10,
    width: '20%',
    height: '35%',
    fontSize: '18px',
    fontWeight: 'bold',
    background: selectedPaymentMethod === 'wechat' ? '#1677ff' : '#fff',
    border: selectedPaymentMethod === 'wechat' ? 'none' : '1px solid #1677ff',
    color: selectedPaymentMethod === 'wechat' ? '#fff' : '#1677ff',
  };

  const checkPay =async (value:string)=>{
    try {
      const res = await isPayUsingPost({
        "out_trade_no": value
      })
      if (res.data) {
        message.success("支付成功");
        getLoginUser();
      } else {
        message.error("支付失败");
      }
    }catch (e){
      console.log(e);
    }

  }
  const getLoginUser = async () => {
  try {
    const res = await getLoginUserUsingGet();
    if (res.data) {
      setLoginUser(res.data);
    }
  }catch (e) {
    history.push('/user/login')
  }
  }
  const handlePay = async (value:number) => {
message.loading("正在创建订单，请勿刷新界面");
    let currentDate = new Date();
    let currentMinute = currentDate.getMinutes();
    let currentSecond = currentDate.getSeconds();
    let orderTime = currentMinute + currentSecond;
    let ordervalue = value+sendValue;
    let out_trade_no = "points"+'value'+ordervalue+`${loginUser?.id}`+orderTime;
    try {
      const res = await buyPointsUsingPost({
        "title":"积分购买",
        "goods_name":"平台积分",
        "out_trade_no":out_trade_no,
        "total_amount":`${actualPayAmount}`,
      })
      if(res.data) {
        const html = res.data;

        Modal.confirm({
          cancelText: '未支付',
          content: '订单是否已经支付',
          centered: true,
          okText: '已支付',
          title: '支付确认',
          onOk: () => {
            message.loading('订单状态查询中，请勿刷新页面',1)
            checkPay(out_trade_no)
          },
          onCancel: () => {
            message.loading('订单状态查询中，请勿刷新页面',1)
            checkPay(out_trade_no)
          },
        })
        const newWindow = window.open('', '_blank', 'width=1500,height=1200');
        newWindow.document.write(html);
        newWindow.document.close();
        getLoginUser();
      }
      else
        message.error('购买失败');
    }catch (e) {
      console.log(e)
    }
  }
  //const onFinish = async (values: any) => {
  //  const hide = message.loading('正在购买...');
   // try {
    //  hide();
    //  const res = await buyPointsUsingPost({
     //   points: sendValue
    //  })
     // if(res.data)
     //   message.success('购买成功');
     // else
    //    message.error('购买失败');
  //  }catch (e) {
  //    console.log(e)
  //  }
 // }
  useEffect(() => {
    getLoginUser();
  }, []);
  return (
    <Layout style={{ marginLeft: '10%',animation: `${fadeIn} 0.5s ease-in-out forwards` }}>
      <Space>
        <div>
          <p
            style={{
              fontSize: '27px',
              fontWeight: 'bold',
              marginTop: 20,
            }}
          >
            购买积分
          </p>
        </div>
      </Space>
      <Card
        style={{
          marginTop: 10,
          width: '60%',
        }}
        title={
          <div style={{ marginTop: 20 }}>
            <a style={{ fontSize: '18px', color: 'gray' }}>当前可用额度：</a>
            <p style={{ fontSize: '32px', fontWeight: 'bold', marginBottom: 10 }}>
               {loginUser?.remainingPoints}
            </p>
          </div>
        }
      >
        <Form name="basic" layout={'vertical'}>
          <Form.Item
            label={<a style={{ fontSize: '18px', color: 'gray' }}>充值积分额度：</a>}
            name="requestParams"
          >
            <InputNumber
              style={{ width: '15%', marginBottom: 5 }}
              changeOnWheel={true}
              defaultValue="100"
              max="10000"
              min="0"
              value={inputValue}
              onChange={handleInputChange}
            />
            <p style={{ display: 'inline-block', marginLeft: '1rem', marginTop: 0,fontSize: '16px', }}>
              实付金额：{actualPayAmount}{" "}元,  平台赠送积分：{sendValue} 个
            </p>
            <br />
            <a style={{ fontSize: '16px',color: 'gray' }}>如您已欠费，充值金额不能低于欠款金额。</a>
          </Form.Item>
          <Divider></Divider>
          <Form.Item label={<a style={{fontSize: '18px', color: 'gray',marginBottom: 5}}>充值方式：</a>}>
            <Button
                style={wechatButtonStyle}
                type={'primary'}
                onClick={() => handlePaymentMethodClick('alipay')}
            >
              支付宝支付
            </Button>
            <br/>
            <br/>
            <a style={{fontSize: '18px', color: 'gray', marginTop: 5}}>
              支付宝实时到账，支持网银、信用卡、储蓄卡和支付宝余额支付。
            </a>
          </Form.Item>
          <Divider></Divider>
          <Form.Item>
            <Radio
              checked={agreementAccepted}
              onChange={handleAgreementChange}
              style={{fontSize: '18px', color: 'gray'}}
            >
              购买须知:
            </Radio>
            <br/>

            <a style={{fontSize: '18px', color: 'gray', marginLeft: 25}}>
              充值金额将优先抵扣未支付和欠费账单。
            </a>
            <br/>
            <a style={{fontSize: '18px', color: 'gray', marginLeft: 25}}>
              充值金额不支持直接开具发票。
            </a>
            <br/>
            <a style={{fontSize: '18px', color: '#ffc53d', marginLeft: 25}}>
              充值后暂不支持退款，请谨慎购买，如有问题请及时联系平台管理员。
            </a>
            <br/>
            <Button
              type="primary"
              htmlType="submit"
              size={'large'}
              disabled={!agreementAccepted}
              style={{marginTop: 20}}
              onClick={() => {
                handlePay(inputValue)
              }}
            >
              确认支付
            </Button>
          </Form.Item>
        </Form>

      </Card>
    </Layout>
  );
};

export default ShopPage;
